﻿/* 
 * author: www.cnblogs.com/luminji
 * date  : 2012/01/16
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace Luminji.Core.Web
{
    public class WebContentHelper
    {

        public static string GetWebContent(string url)
        {
            using (Stream stream = GetWebStream(url))
            {
                return GetWebContent(stream);
            }
        }

        public static string GetWebContent(Stream stream)
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }

        public static Stream GetWebStream(string url)
        {
            var request = HttpWebRequest.Create(url);
            var response = request.GetResponse();
            return response.GetResponseStream();
        }

        public static void SendSample()
        {
            string urlPost = "http://www.adventureworks.com/api/post.xml";
            string postData = "status=Something strange.";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteData = encoding.GetBytes(postData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPost);
            request.Credentials = new NetworkCredential("name", "pwd");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(byteData, 0, byteData.Length);
            requestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }
    }
}
